package cn.liccshop.core.utils;

import cn.liccshop.sys.constants.Constants;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author LiCC
 * @program LiCCShop
 * @description 七牛云配置
 * @since 2019-04-11-15:03
 */
public class QiniuUtils {

    public static Map<String, String> getQiniuInfo(MultipartFile[] files){

        Map<String, String> map = new HashMap<>();
        Configuration cfg = new Configuration(Zone.zone2());
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(Constants.QINIU_ACCESSKEY, Constants.QINIU_SECRETKEY);
        String token = auth.uploadToken(Constants.QINIU_BUCKET);
        try {
            for (MultipartFile file : files) {
                String imgName = Constants.QINIU_PREFIX_NAME + getImgName();
                Response response = uploadManager.put(file.getBytes(), imgName, token);
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                map.put(file.getOriginalFilename(),"http://lccabc.cn/"+putRet.key);
            }
        } catch (QiniuException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return map;
    }

    private static String getImgName(){
        String name = DigestUtils.md5Hex(UUID.randomUUID().toString().replaceAll("-", "") + ":" + System.currentTimeMillis());
        return name;
    }
}
